package com.wangshuqi.app;

import com.wangshuqi.spring.BeanPostProcessor;
import com.wangshuqi.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws Exception {
        if (beanName.equals("userService")) {
            System.out.println("userService初始化前加载");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws Exception {
        if (beanName.equals("userService")) {
            // newProxyInstance(类加载器、)
            Object aopBean = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("AOP Before...");
                    Object invoke = method.invoke(bean, args);
                    System.out.println("AOP After...");
                    return invoke;
                }
            });
            return aopBean;
        }
        return bean;
    }
}
